<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="search_name" placeholder="请输入角色名称" style="width: 200px;" class="filter-item" />
      <el-button style="margin-left: 20px" class="filter-item" type="primary" icon="el-icon-search" @click="getRole">
        查询
      </el-button>
      <el-button style="margin-left: 20px" class="filter-item" type="primary" @click="handleAddRole">添加角色</el-button>
    </div>
    <el-table v-loading="loading" :data="RoleList" style="width: 100%;margin-top:30px;" border>
      <el-table-column align="center" label="角色ID" width="100">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="角色名称" width="100">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="角色简介" width="220">
        <template slot-scope="scope">
          {{ scope.row.info }}
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="父级角色">
        <template slot-scope="scope">
          {{ scope.row.p_name||'无' }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="是否有效">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-color="#13ce66"
            :active-value="0"
            :inactive-value="1"
            @change="checkStatus(scope)"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑角色':'新增角色'">
      <el-form :model="RoleAdd" label-width="80px" label-position="left">
        <el-form-item label="角色名称">
          <el-input v-model="RoleAdd.name" placeholder="输入角色名称" />
        </el-form-item>
        <el-form-item label="角色简介">
          <el-input
            v-model="RoleAdd.info"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="请输入角色简介"
          />
        </el-form-item>
        <el-form-item label="父级角色">
          <el-select v-model="RoleAdd.pid" filterable clearable placeholder="请选择父级角色">
            <el-option
              v-for="item in RoleOption"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选择权限">
          <el-tree
            ref="tree"
            :data="PerTree"
            show-checkbox
            default-expand-all
            node-key="id"
            highlight-current
            :default-checked-keys="def_key"
            :props="defaultProps"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="clearLost">取消</el-button>
        <el-button type="primary" @click="confirmRole">确定</el-button>
      </div>
    </el-dialog>

    <el-pagination
      style="float: right;margin-top: 20px"
      :page-size="limit"
      layout="total, prev, pager, next, jumper"
      :total="total"
      :hide-on-single-page="true"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { GetPermissionTree, updateRole, addRole, GetRoleList, CheckRoleStatus, GetRoleOption, GetCheckedTree, DelRole } from '@/api/role'
import { deepClone } from '@/utils'

export default {
  data() {
    return {
      RoleList: [],
      def_key: [],
      PerTree: [],
      dialogVisible: false,
      dialogType: 'new',
      RoleAdd: {
        name: '',
        info: '',
        pid: ''
      },
      limit: 0,
      total: 0,
      RoleOption: [],
      search_name: '',
      defaultProps: {
        children: 'child',
        label: 'name'
      },
      loading: false
    }
  },
  created() {
    this.PermissionTree()
    this.getRole()
    this.GetRoleOption()
  },
  methods: {
    async PermissionTree() {
      const res = await GetPermissionTree()
      switch (res.code) {
        case -1:
          this.$message({
            type: 'error',
            message: res.msg || 'Error'
          })
          break
        case 200:
          this.PerTree = res.data
          break
      }
    },
    handleAddRole() {
      this.RoleAdd = {}
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    async checkStatus(e) {
      const res = await CheckRoleStatus(e.row.status, e.row.id)
      switch (res.code) {
        case -1:
          this.$message({
            type: 'error',
            message: res.msg || 'Error'
          })
          break
        case 200:
          this.$message({
            type: 'success',
            message: res.msg || 'Success'
          })
          break
      }
    },
    async GetRoleOption() {
      const res = await GetRoleOption()
      this.RoleOption = res.data
    },
    async confirmRole() {
      const tree = this.$refs.tree.getCheckedNodes()
      const isEdit = this.dialogType === 'edit'
      if (isEdit) {
        const res = await updateRole(this.RoleAdd, tree)
        switch (res.code) {
          case -1:
            this.$message({
              type: 'error',
              message: res.msg || 'Error'
            })
            break
          case 200:
            this.$message({
              type: 'success',
              message: res.msg || 'Success'
            })
            this.dialogVisible = false
            // location.reload()
            break
        }
      } else {
        const res = await addRole(this.RoleAdd, tree)
        switch (res.code) {
          case -1:
            this.$message({
              type: 'error',
              message: res.msg || 'Error'
            })
            break
          case 200:
            this.$message({
              type: 'success',
              message: res.msg || 'Success'
            })
            this.dialogVisible = false
            this.loading = true
            location.reload()
            this.loading = false
            break
        }
      }
    },
    async handleCurrentChange(e) {
      const res = await GetRoleList(this.search_name, e, this.limit)
      this.RoleList = res.data.res
      this.total = res.data.fenye.total
      this.limit = parseInt(res.data.fenye.limit)
    },
    async getRole() {
      const res = await GetRoleList(this.search_name, this.page, this.limit)
      // console.log(res.data.res)
      this.RoleList = res.data.res
      this.total = res.data.fenye.total
      this.limit = parseInt(res.data.fenye.limit)
    },
    async handleEdit(res) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.RoleAdd = deepClone(res.row)
      const checked_ids = await GetCheckedTree(res.row.id)
      const list_key = checked_ids.data
      // console.log(checked_ids.data)
      this.def_key = []
      list_key.forEach((v) => {
        this.$nextTick(() => {
          this.$refs.tree.setChecked(v.id, true, false)
        })
      })
    },
    async handleDelete(res) {
      const id = res.row.id
      const response = await DelRole(id)
      switch (response.code) {
        case -1:
          this.$message({
            type: 'error',
            message: response.msg || 'Error'
          })
          break
        case 200:
          this.$message({
            type: 'success',
            message: response.msg || 'Success'
          })
          location.reload()
          break
      }
    },
    async clearLost() {
      this.dialogVisible = false
      const rootNode = this.$refs.tree.getNode(this.PerTree[0].id).parent
      this.travelNodes(rootNode)
    },

    travelNodes(tmpRoot) {
      // 选中该节点
      tmpRoot.checked = false
      // 叶子节点
      if (tmpRoot.childNodes.length === 0) {
        return false
        // eslint-disable-next-line brace-style
      }
      // 不是叶子节点,递归遍历
      else {
        var tmpChildNoes = tmpRoot.childNodes
        for (let i = 0; i < tmpChildNoes.length; i++) {
          this.travelNodes(tmpChildNoes[i])
        }
      }
    }
  }
}
</script>

<style scoped>

</style>
